import { FC } from 'react';

interface VirtualListProps {
  list: string[];
  containerHeight: number;
  bufferCount: number;
}

// 导出一个名为VirtualList的函数组件，接收一个VirtualListProps类型的参数
export const VirtualList: FC<VirtualListProps> = ({
  list,
  containerHeight,
  bufferCount,
}: VirtualListProps) => {
  // 创建一个ref，用于获取容器元素的引用
  const containerRef = useRef<HTMLDivElement>(null);
  // 创建一个state，用于保存滚动条的位置
  const [scrollTop, setScrollTop] = useState(0);

  // 创建一个state，用于保存每个item的高度
  const [itemHeights, setItemHeights] = useState<number[]>([]);

  // 获取每个item的高度
  const getItemHeight = (index: number) => {
    return index % 2 === 0 ? 50 : 75;
  };

  // 在list发生变化时，计算每个item的高度，并更新state
  useEffect(() => {
    const heights = list.map((_, index) => getItemHeight(index));
    // const heights = itemRefs?.current?.map((ref) =>
    //   ref ? ref.offsetHeight : 0
    // )
    setItemHeights(heights);
  }, [list]);
  console.log(itemHeights, 'itemHeights');

  // 计算整个文档的总高度
  const docTotalHeight = itemHeights.reduce((acc, height) => acc + height, 0);

  // 获取可见的item的索引
  const getVisibleItemsIndex = () => {
    let accumulateHeight = 0;
    let startIndex = 0;
    let endIndex = list.length - 1;
    for (let i = 0; i < list.length; i++) {
      const itemHeight = getItemHeight(i);
      accumulateHeight += itemHeight;
      if (accumulateHeight > scrollTop) {
        startIndex = i;
        break;
      }
    }
    accumulateHeight = 0;
    for (let i = startIndex; i < list.length; i++) {
      accumulateHeight += itemHeights[i];
      if (accumulateHeight > containerHeight) {
        endIndex = i;
        break;
      }
    }
    return {
      startIndex: Math.max(startIndex - bufferCount, 0),
      endIndex: Math.min(endIndex + bufferCount, list.length - 1),
    };
  };

  // 获取可见的item的索引
  const { startIndex, endIndex } = getVisibleItemsIndex();
  console.log(startIndex, endIndex, 'startIndex, endIndex');
  // 处理滚动事件
  const handleScroll = () => {
    if (containerRef.current) {
      setScrollTop(containerRef.current.scrollTop);
    }
  };

  // 在组件挂载时，添加滚动事件监听器，在组件卸载时，移除滚动事件监听器
  useEffect(() => {
    const viewport = containerRef.current;
    if (viewport) {
      viewport.addEventListener('scroll', handleScroll);
      return () => {
        viewport.removeEventListener('scroll', handleScroll);
      };
    }
  }, []);

  // 渲染每个item
  const renderItems = (item: string) => {
    return <span>{item}</span>;
  };

  // 创建一个数组，用于保存可见的item
  const items = [];

  // 计算可见item的topOffset
  let topOffset = 0;
  for (let i = 0; i < startIndex; i++) {
    topOffset += itemHeights[i] || 0;
  }
  // 渲染可见的item
  for (let i = startIndex; i <= endIndex; i++) {
    items.push(
      <div
        key={i}
        // ref={el=>{
        //   // itemRefs.current[i] = el
        // }}
        style={{
          top: `${topOffset}px`,
          position: 'absolute',
          width: '100%',
        }}
      >
        {renderItems(i)}
      </div>,
    );
    topOffset += itemHeights[i] || 0;
  }
  return (
    // 渲染容器
    <div
      ref={containerRef}
      style={{
        height: containerHeight,
        width: '100%',
        overflow: 'auto',
        position: 'relative',
        border: '1px solid #ccc',
      }}
    >
      <div style={{ height: `${docTotalHeight}px`, position: 'relative' }}>
        {items}
      </div>
    </div>
  );
};
